package digui;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;

public class basic1302 {

    //层序遍历
    public static  void  w(TreeNode root){
        if(root==null){
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()){
            TreeNode cur = queue.poll();
            System.out.println(cur.val);
            if (cur.left!=null){
                queue.add(cur.left);
            }
            if (cur.right!=null){
                queue.add(cur.right);
            }
        }
    }

    //求最大宽度
    public static  void  w_num(TreeNode root){
        if(root==null){
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        HashMap<TreeNode, Integer> levelMap = new HashMap<>();
        levelMap.put(root,1);
        int curLevel=1;
        int curLevelNodes=0;
        int max=Integer.MIN_VALUE;
        while (!queue.isEmpty()){
            TreeNode cur = queue.poll();
            int curNodeLevel = levelMap.get(cur);
            if (curLevel==curNodeLevel){
                curLevelNodes++;
            }
            else {
                max=Math.max(max,curLevelNodes);
                curLevel++;
                curLevelNodes=1;

            }
            if (cur.left!=null){
                levelMap.put(cur.left,curNodeLevel+1);
                queue.add(cur.left);
            }
            if (cur.right!=null){
                levelMap.put(cur.right,curNodeLevel+1);
                queue.add(cur.right);
            }
        }
        System.out.println(max);
    }


    int maxtip=-1;
    int total=0;
    public int deepestLeavesSum(TreeNode root) {
        dfs(root,0);
        return total;
    }

   public  void dfs(TreeNode root,int t){
        if(root==null) return ;
        if(t>maxtip){
            maxtip=t;
            total= root.val;
        }
        else if(t==maxtip){
            total+=root.val;
        }
        dfs(root.left,t+1);
        dfs(root.right,t+1);
    }


    public static void main(String[] args) {

        TreeNode treeNode1 = new TreeNode(1);
        TreeNode treeNode2= new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode4= new TreeNode(4);
        TreeNode treeNode5= new TreeNode(5);
        TreeNode treeNode6= new TreeNode(6);
        TreeNode treeNode7= new TreeNode(7);
        TreeNode treeNode8= new TreeNode(8);
        treeNode1.left=treeNode2;
        treeNode1.right=treeNode3;
        treeNode2.left=treeNode4;
        treeNode2.right=treeNode5;
        treeNode4.left=treeNode7;
        treeNode3.right=treeNode6;
        treeNode6.right=treeNode8;
        basic1302 basic1302 = new basic1302();
        System.out.println(basic1302.deepestLeavesSum(treeNode1));
    }


}
